/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package refactoring;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


/**
 *
 * @author Vsevolod Kazakov
 */
public class SingleHymn {
    static Proxy proxy;
    static {
        proxy = Settings.getProxy();
    }
    
    private static HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {            
            return true;
        }
    };
    
    TrustManager[] trustAllCerts = new TrustManager[] {
       new X509TrustManager() {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
          }

          public void checkClientTrusted(X509Certificate[] certs, String authType) {  }

          public void checkServerTrusted(X509Certificate[] certs, String authType) {  }

       }
    };
            
    

    static class Line2 {
        int numberRuOld;
        int numberEn;
    }
    
    int numberRu;
    int numberRuOld;
    int numberEn;
    String firstCoupletLine;
    String firstCoupletChar;
    
    String firstPripevLine;
    String firstPripevChar;
    
    String text = "";
    String mainTheme;
    String subTheme;
    String tuneFilename;
    String midiFilename;
    
    static SingleHymn CreateSingleHymn() {
        return new SingleHymn();
    }
    private SingleHymn() {        
        
    }
    
    public String downLoadMidi(boolean tune, String midiFolder) {
        try {
            String fileName;
            String append;
            String numAppend = "";
            if (this.numberEn == 0) {
                return null;
            }
            if(this.numberRu < 100) {
                numAppend += "0";
                if(this.numberRu < 10) {
                    numAppend += "0";
                }
            }
            if (tune) {                
                fileName = tuneFilename = "tune_" + numAppend + this.numberRu + ".midi";
                append = "/f=tune";                
            } else {
                fileName = midiFilename = "midi_" + numAppend + this.numberRu + ".mid";
                append = "/f=mid";
            }
            File checkF = new File(midiFolder + fileName);
            if(checkF.exists() && !checkF.isDirectory()) {
                return fileName;
            }
            
            String urlName = Settings.SearchStrings.searchStr1 + "en/hymn/h/" + Integer.toString(numberEn) + append;

            HttpsURLConnection httpsConnection = null;
            InputStream is = null;

            SSLContext sc;

            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            URL urls = new URL(urlName);            
            URLConnection con = null;
            try {
                con = urls.openConnection(proxy);
            } catch (Exception e) {
                System.out.println(e);
            }

            is = con.getInputStream();

            byte bytes[] = new byte[100];

            File f = new File(midiFolder + fileName);
            FileOutputStream fos = new FileOutputStream(f);

            int readResult;
            while ((readResult = is.read(bytes)) > 0) {
                fos.write(bytes, 0, readResult);
            }
            fos.close();
            is.close();
        } catch (IOException ioe) {
            System.out.println("ioe ex: " + ioe.getMessage());
            tuneFilename = "";
        } catch (NoSuchAlgorithmException nsae) {
            System.out.println("nsae ex: " + nsae.getMessage());
        } catch (KeyManagementException ex) {
            System.out.println("ex: " + ex.getMessage());
        }
        return tuneFilename;
    }   
  
    
    public boolean initHymn(final String fileName) throws IllegalArgumentException {
        BufferedReader br = null;
        Reader reader = null;
        try {
            reader = new InputStreamReader(new FileInputStream(fileName), "Windows-1251");
            br = new BufferedReader(reader);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(SingleHymn.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(SingleHymn.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        String line;
        try {
            int lineNumber = 1;
            while ((line = br.readLine()) != null) {
                if(lineNumber == 1) {
                    numberRu = parseLine1(line);
                }
                if (lineNumber == 2) {
                   Line2 l = parseLine2(line);
                   numberEn = l.numberEn;
                   numberRuOld = l.numberRuOld;
                }
                if (lineNumber == 3) {
                    mainTheme = parseLine3(line);
                }
                if (lineNumber == 4) {
                    subTheme = parseLine4(line);
                    if (subTheme == null) {
                        subTheme = mainTheme;
                    }
                    if (subTheme.equals("")) {
                        subTheme = mainTheme;
                    }
                }
                if (firstCoupletLine == null && line.indexOf("1.") >= 0 && lineNumber < 10) {
                    text += line + "\n";
                    line = br.readLine();
                    lineNumber++;
                    firstCoupletLine = line;
                    firstCoupletChar = line.substring(0,1);
                    if(firstCoupletChar.indexOf("«") >= 0){
                        firstCoupletChar = line.substring(1,2);
                    }
                }
                
                if (firstPripevLine == null && line.indexOf("ПРИПЕВ") >= 0 && lineNumber < 30) {
                    text += line + "\n";
                    line = br.readLine();
                    lineNumber++;
                    firstPripevLine = line;
                    firstPripevChar = line.substring(0,1);
                    if(firstPripevChar.indexOf("«") >= 0){
                        firstPripevChar = line.substring(1,2);
                    }
                }
                text += line + "\n";
                lineNumber++;

            }

            
        
            br.close();        
        } catch (IOException ex) {
            
        }
        return true;
    }
    
    static private int parseLine1(String line) {
        return Integer.decode(line);
    }
    
    static private Line2 parseLine2(String line) {
        Line2 obj;
        obj = new Line2();
        int ruIndexStart = line.indexOf("(РС");
        int ruIndexEnd = 1;
        if (ruIndexStart >= 0) {
            
            ruIndexEnd = line.indexOf(",", ruIndexStart);
            if(ruIndexEnd < 0) {
                ruIndexEnd = line.indexOf(")", ruIndexStart);
            }
            String subString = line.substring(ruIndexStart + 3, ruIndexEnd);            
            obj.numberRuOld = Integer.decode(subString);
        } else {
            obj.numberRuOld = 0;
        }
        int enIndexStart = line.indexOf("А");
        int enIndexEnd = line.indexOf(")", enIndexStart);
        if (enIndexStart >= 0) {
            String subStr = line.substring(enIndexStart + 1, enIndexEnd);
            obj.numberEn = Integer.decode(subStr);
        } else {
            obj.numberEn = 0;
        }
        return obj;
    }
        
    static private String parseLine3(String line) {
        return line;
    }
    
    static private String parseLine4(String line) {
        return line;
    }
}
